package com.bdqn.controller;

import com.bdqn.service.UserService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * <Description> <br>
 *
 * @author tao<br>
 * @version 1.0<br>
 * @taskId: <br>
 * @createDate 2019/10/15 11:11 <br>
 * @see com.bdqn.controller <br>
 */
@Controller
@RequestMapping("/generate")
public class MainController {
    @Resource
    Configuration cfg;

    @Autowired
    private UserService userService;

    @GetMapping("/welcome")
    @ResponseBody
    public String main(Model model){
        String w="admin";
        Map root = new HashMap();
        root.put("w",userService.getMaxUser().getUsername());
        freeMarkerContent(root);
        return "生成成功";
    }

    private void freeMarkerContent(Map<String,Object> root){
        try {
            Template temp = cfg.getTemplate("staticPage.ftl");
            //以classpath下面的static目录作为静态页面的存储目录，同时命名生成的静态html文件名称
            String path =this.getClass().getResource("/").toURI().getPath()+"static/test.html";
            File file = new File(path);
            File fileParent = file.getParentFile();//返回的是File类型,可以调用exsit()等方法
            String fileParentPath = file.getParent();//返回的是String类型
            if (!fileParent.exists()) {
                fileParent.mkdirs();// 能创建多级目录
            }
            if (!file.exists()) {
                file.createNewFile();//有路径才能创建文件
            }
            Writer writer = new FileWriter(file);
            temp.process(root, writer);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
}
